﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GcTrackableRace.ScoreCalculator.Helpers
{
	class Haversine
	{
		// Note: Distances take from http://en.wikipedia.org/wiki/Earth_radius

		const double _EarthRadiusInKm = 6371;
		const double _EarthRadiusInMiles = 3959;
		const double _d2r = (Math.PI / 180D);

		public static double InKilometers(double lat1, double long1, double lat2, double long2)
		{
			double dlong = (long2 - long1) * _d2r;
			double dlat = (lat2 - lat1) * _d2r;
			double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
			double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
			double d = _EarthRadiusInKm * c;

			return d;
		}

		public static double InMiles(double lat1, double long1, double lat2, double long2)
		{
			double dlong = (long2 - long1) * _d2r;
			double dlat = (lat2 - lat1) * _d2r;
			double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
			double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
			double d = _EarthRadiusInMiles * c;

			return d;
		}
	}
}
